<template>
  <base-breadcrumb
    v-loading="loadingState.isDetail"
    :title="titleName"
  >
    <a-form-model
      ref="ruleForm"
      :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
      :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
      :model="queryParam"
      :rules="rules"
    >
      <div class="box">
        <a-card>
          <title-name title="项目信息" />
          <a-row :gutter="24">
              <a-col span="16">
            <a-form-model-item label="所属单位" prop="projectId">
              <org-tree-select 
                               v-model="queryParam.projectId" 
                               isAutoSelectFirst checkStrictly 
                               @select="selectOrg"></org-tree-select>
            </a-form-model-item>
          </a-col>
            <!-- <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="所属分公司"
                prop="branchComId"
              >
                <SelectSubCompany
                  v-model="queryParam.branchComId"
                  placeholder="请选择"
                  @selectChange="handleCompanyChange"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="项目名称"
                prop="projectId"
              >
                <SelectProject
                  ref="SelectProject"
                  v-model="queryParam.projectId"
                  placeholder="请选择"
                  :form="queryParam"
                  :is-clear="!$route.query.id"
                  key-value="branchComId"
                />
              </a-form-model-item>
            </a-col> -->
          </a-row>
        </a-card>
      </div>
      <div class="box">
        <a-card>
          <title-name title="执行案件信息" />
          <a-row :gutter="24">
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="函件编号"
                prop="code"
              >
                <BaseInput
                  v-model="queryParam.code"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="函件名称"
                prop="name"
              >
                <BaseInput
                  v-model="queryParam.name"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="发函单位"
                prop="seddingUnit"
              >
                <BaseInput
                  v-model="queryParam.seddingUnit"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="申请执行人"
                prop="executor"
              >
                <BaseInput
                  v-model="queryParam.executor"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="被执行人"
                prop="byExecutor"
              >
                <BaseInput
                  v-model="queryParam.byExecutor"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="收到时间"
                prop="receivedDate"
              >
                <a-date-picker
                  v-model="queryParam.receivedDate"
                  placeholder="请选择"
                  value-format="YYYY-MM-DD"
                  type="date"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col
              :md="24"
              :sm="24"
            >
              <a-form-model-item label="备注">
                <BaseTextarea
                  v-model="queryParam.remark"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="24"
              :sm="24"
            >
              <a-form-model-item
                label="主要内容"
                prop="content"
              >
                <BaseTextarea
                  v-model="queryParam.content"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item label="创建人">
                <BaseInput
                  v-model="queryParam.creatorName"
                  :disabled="true"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item label="创建时间">
                <BaseInput
                  v-model="queryParam.createTime"
                  :disabled="true"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
      </div>
      <div class="box">
        <a-card>
          <title-name title="附件列表" />
          <UploadTableNew
            ref="uploadTable"
            mode="add"
            :init-file-list="queryParam.fileList"
            :need-page="false"
            business-code="LCM12"
          />
        </a-card>
      </div>
    </a-form-model>
    <div
      class="operation page-btn-right-top"
    >
      <a-button
        type="primary"
        :loading="loadingState.SUBMITTED"
        @click="handleSubmit('SUBMITTED')"
      >
        提交
      </a-button>
      <a-button
        class="ml12"
        @click="handleClose"
      >
        关闭
      </a-button>
    </div>
  </base-breadcrumb>
</template>

<script>
import { getDetail, addData, editData } from '@/api/legal/caseAndLetter/caseManage.js'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject'
import Selector from '@/components/Select/Selector'
import Vue from 'vue'
import Moment from 'moment'
import { packageConfirm } from '@/utils/baseAction.js'

export default {
  name:'a'+Date.now(),
  components: {
    SelectSubCompany,
    SelectProject,
  },
  data() {
    return {
      loadingState: {
        isDetail: false,
        SUBMITTED: false
      },
      titleName: undefined,
      loading: false,
      queryParam: {
        id: this.$route.query.id,
        fileList: []
      },
      rules: {
        // branchComId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择所属公司', trigger: 'change' }],
        code: [{ required: true, message: '请输入', trigger: 'change' }],
        name: [{ required: true, message: '请输入', trigger: 'change' }],

        seddingUnit: [{ required: true, message: '请选择', trigger: 'change' }],
        executor: [{ required: true, message: '请输入', trigger: 'change' }],
        byExecutor: [{ required: true, message: '请输入', trigger: 'change' }],
        receivedDate: [{ required: true, message: '请选择', trigger: 'change' }],
        remark: [{ required: true, message: '请输入', trigger: 'change' }],
        content: [{ required: true, message: '请输入', trigger: 'change' }],
      }
    }
  },
  created() {
    this.initPage()
    this.getDetailReq()
  },
  methods: {
    initPage() {
      if (this.$route.query.id) {
        this.titleName = '函件编辑'
      } else {
        this.titleName = '函件新增'
      }
      const userInfo = Vue.getAcloudProvider().getUserInfo()
      const curDate = Moment(new Date()).format('YYYY-MM-DD')
      this.queryParam = {
        ...this.queryParam,
        creatorName: userInfo.name,
        createTime: curDate
      }
    },
    async getDetailReq() {
      try {
        if (!this.$route.query.id) return
        const params = {
          id: this.$route.query.id
        }
        this.loadingState.isDetail = true
        const res = await getDetail(params)
        this.queryParam = {
          ...this.queryParam,
          ...res.data,
          legalTypeId: res.data?.legalType?.id,
          amount: res.data?.amountVO?.amount
        }
      } catch (e) {
        console.error(e)
      }
      this.loadingState.isDetail = false
    },
    handleCompanyChange(val) {
      this.queryParam = {
        ...this.queryParam,
        branchComName: val.orgName,
      }
    },
    selectOrg(val) {
      if (val && val.length) {
        this.queryParam.projectName = val[val.length-1].projectName
        this.handleCompanyChange(val[val.length-2])
      }
    },
    /**
     * 保存草稿、提交等操作
     * @param {String} actionName 'DRAFT': 保存草稿  'SUBMITTED'：提交
     */
    handleSubmit(actionName) {
      if (actionName === 'SUBMITTED') {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            this.$message.warning('请填写完整')
            return
          }
          packageConfirm({
            content: '请确认是否要提交?'
          }).then((flag) => {
            if (flag === 'cancel') return
            this.invokeSave(actionName)
          })
        })
      } else {
        this.invokeSave(actionName)
      }
    },
    /**
     * 保存接口调用
     */
    async invokeSave(actionName) {
      if (this.loadingState[actionName]) return
      try {
        this.loadingState[actionName] = true
        const { allList } = this.$refs.uploadTable.getChangedFileIds()
        const { amount, branchComId, branchComName, projectId } = this.queryParam
        // const projectName = this.$refs.SelectProject.getValueName(projectId)
        const params = {
          ...this.queryParam,
          involvedAmount: {
            amount: amount
          },
          projectInfo: {
            branchComId: branchComId,
            branchComName: branchComName,
            projectId: projectId,
            projectName: this.queryParam.projectName
          },
          fileList: allList
        }
        const fn = !this.$route.query.id ? addData : editData
        await fn(params)
        this.loadingState[actionName] = false
        this.$message.success(actionName === 'DRAFT' ? '保存成功' : '提交成功')
        this.$refs.uploadTable.batchDeleteFile() // 删除文件
        this.handleClose()
      } catch (e) {
        console.error(e)
        this.loadingState[actionName] = false
      }
    },
    handleClose() {
      this.$close()
    }
  }
}
</script>

<style scoped>
.box {
  margin: 12px 0;
}
</style>
